package com.dm.cloud.utils;

import com.dm.cloud.common.CloudConstant;
import com.dm.cloud.common.CommonDto;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 非auth服务处理实体类工具类 解析从网关服务中获取到的username信息
 * auth服务自身带有认证服务，可以自行解析
 * @param <T>
 */
public class DtoPreOpratrionUtils<T> {

    public void preInsert(T t){
        if(t instanceof CommonDto) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String username = request.getHeader(CloudConstant.GATEWAY_USERNAME);

            //用户信息
            CommonDto t1 = (CommonDto) t;
            t1.setCreateBy(username);
            t1.setUpdateBy(username);

            Date dt = new Date();
            t1.setCreateDate(dt);
            t1.setUpdateDate(dt);
        }
    }

    public void preUpdate(T t){
        if(t instanceof CommonDto) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String username = request.getHeader(CloudConstant.GATEWAY_USERNAME);

            CommonDto t1 = (CommonDto) t;
            t1.setUpdateBy(username);

            Date dt = new Date();
            t1.setUpdateDate(dt);
        }
    }
}
